package com.ophiux.wechat.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ophiux.common.core.base.Result;
import com.ophiux.common.core.exception.APIException;
import com.ophiux.common.core.utils.DateUtils;
import com.ophiux.wechat.mapper.OphiuxProblemAnswerMapper;
import com.ophiux.wechat.model.dto.OphiuxProblemAnswerAddDTO;
import com.ophiux.wechat.model.entity.OphiuxAppUserAnswer;
import com.ophiux.wechat.model.entity.OphiuxProblemAnswer;
import com.ophiux.wechat.service.OphiuxAppUserAnswerService;
import com.ophiux.wechat.service.OphiuxProblemAnswerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @desc:问题-答案记录表接口实现层
 * @autor: hhl
 * @date: 2023-07-19 14:57:15<br>
 */
@Service
public class OphiuxProblemAnswerServiceImpl extends ServiceImpl<OphiuxProblemAnswerMapper, OphiuxProblemAnswer> implements OphiuxProblemAnswerService {

    @Autowired
    private OphiuxAppUserAnswerService ophiuxAppUserAnswerService;

    @Value("${ophiux.server.enabled}")
    private boolean enabled;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveAnswer(OphiuxProblemAnswerAddDTO vo) {
        if (!enabled && !LocalDateTime.now().isBefore(LocalDateTimeUtil.parse("2023-08-31 00:00:00",DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))) {
            return Result.fail("服务不可用，请联系管理员");
        }

        long count = ophiuxAppUserAnswerService.count(new LambdaQueryWrapper<OphiuxAppUserAnswer>().eq(OphiuxAppUserAnswer::getPatientId, vo.getPatientId())
                .like(OphiuxAppUserAnswer::getCreatedTime, DateUtils.getDate("yyyy-MM-dd")));
        if (count > 0) {
            return Result.fail("请勿重复提交");
        }

        Integer recordId = ophiuxAppUserAnswerService.init(vo.getPatientId(), vo.getUseType());

        if (ObjectUtils.isEmpty(vo.getAnswerList()) || vo.getAnswerList().size() < 1) {
            throw new APIException("请选择答案");
        }
        vo.getAnswerList().forEach(ophiuxProblemAnswer -> {
            ophiuxProblemAnswer.setAnswerRecordId(recordId);
            ophiuxProblemAnswer.setCreatedTime(LocalDateTimeUtil.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        });

        boolean isOk = this.saveBatch(vo.getAnswerList());
        Assert.isTrue(isOk, "保存失败");
        return Result.successMsg("保存成功");
    }
}
